package com.css.fxfzypg.modules.similitudeAnalyse.utils;

import com.css.fxfzypg.modules.similitudeAnalyse.entity.RealEarthquakeEntity;
import com.css.fxfzypg.util.HttpClientUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author y1fan
 * @create 2022-09-01 15:56
 */

public class Xml2ObjectUtil {

    public static List<RealEarthquakeEntity> getRealEarthquakeEntity(String url){
        String s = HttpClientUtil.doPost(url);
        InputStream is = null;
        try {
            SAXReader reader = new SAXReader();
            is = new ByteArrayInputStream(s.getBytes("UTF-8"));
            Document doc = reader.read(is);
            Element root = doc.getRootElement();
            List<Element> article = root.elements("item");
         /*   Element element = article.get(0);*/
            List<RealEarthquakeEntity> list=new ArrayList<>();
            for (Element element : article) {
                String cata_id = element.elementText("cata_id");
                String o_time = element.elementText("o_time");
                String m = element.elementText("m");
                String epi_lat = element.elementText("epi_lat");
                String epi_lon = element.elementText("epi_lon");
                if(new BigDecimal(epi_lon).compareTo(BigDecimal.valueOf(73.5))<0 || new BigDecimal(epi_lon).compareTo(BigDecimal.valueOf(135.05))>0){
                    continue;
                }
                if(new BigDecimal(epi_lat).compareTo(BigDecimal.valueOf(4))<0 || new BigDecimal(epi_lat).compareTo(BigDecimal.valueOf(53.5))>0){
                    continue;
                }
                String epi_depth = element.elementText("epi_depth");
                String auto_flag = element.elementText("auto_flag");
                String location_c = element.elementText("location_c");
                RealEarthquakeEntity entity=new RealEarthquakeEntity();
                entity.setCataId(cata_id);
                entity.setOTime(o_time);
                entity.setM(m);
                entity.setEpiLat(epi_lat);
                entity.setEpiLon(epi_lon);
                entity.setEpiDepth(epi_depth);
                entity.setAutoFlag(auto_flag);
                entity.setLocationC(location_c);
                list.add(entity);
            }
         /*   System.out.println(article.size());
            System.out.println(realEarthquakeEntity.toString());*/
            return list;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
